package com.bobo.aspect;


import com.bobo.annotation.AutoFill;
import com.bobo.constant.AutoFillConstant;
import com.bobo.context.BaseContext;
import com.bobo.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义切面类
 */
@Aspect
@Component
@Slf4j
public class FillAspect {
    //1.定义切入点
    @Pointcut("execution(* com.bobo.mapper.*.*(..)) && @annotation(com.bobo.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void Pointcut(JoinPoint joinPoint) throws Exception {
        //获得当前数据库操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //获得方法签名对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class); //获取注解
        OperationType operationType = annotation.value(); //获取OperationType
        //获取操作的对象实体
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        //约定需要AutoFill的实体放在方法的第一个参数
        Object entity = args[0];
        //准备需要的变量
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //判断当前的方法
        if(operationType == OperationType.INSERT){
            //通过反射获取方法
            Method setCreateTime = entity.getClass().getMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateTime = entity.getClass().getMethod("setUpdateTime", LocalDateTime.class);
            Method setCreateUser = entity.getClass().getMethod("setCreateUser", Long.class);
            Method setUpdateUser = entity.getClass().getMethod("setUpdateUser", Long.class);
            //invoke使用方法
            setCreateTime.invoke(entity, now);
            setUpdateTime.invoke(entity, now);
            setCreateUser.invoke(entity, currentId);
            setUpdateUser.invoke(entity, currentId);
        }else if(operationType == OperationType.UPDATE){
            Method setUpdateTime = entity.getClass().getMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = entity.getClass().getMethod("setUpdateUser", Long.class);
            setUpdateTime.invoke(entity, now);
            setUpdateUser.invoke(entity, currentId);

        }
    }


}
